﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace GenericCommTool
{
    /// <summary>
    /// 生成
    /// </summary>
    public class GenericService : IGenericService
    {
        private readonly string TemplatePath = "templates";
        private readonly string _projBasicPath;
        private readonly string _projName;

        public GenericService(string projBasicPath, string projectName)
        {
            _projBasicPath = projBasicPath;
            _projName = projectName;
        }

        private string GetTemplate(string name)
        {
            var fileName = $"{TemplatePath}/{name}";
            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException(name);
            }

            return File.ReadAllText(fileName, Encoding.UTF8);
        }

        public string Generic(string className, string description)
        {
            var iRepo = GetTemplate("IRepository.cstp").ReplaceTemp(className, description, _projName);
            var repo = GetTemplate("Repository.cstp").ReplaceTemp(className, description, _projName);
            var iServ = GetTemplate("IService.cstp").ReplaceTemp(className, description, _projName);
            var serv = GetTemplate("Service.cstp").ReplaceTemp(className, description, _projName);
            var iRepoName = $"I{className}Repository.cs";
            var repoName = $"{className}Repository.cs";
            var iServName = $"I{className}Service.cs";
            var servName = $"{className}Service.cs";

            Write($"{_projBasicPath}/{_projName}.IRepositories/{iRepoName}", iRepo);
            Write($"{_projBasicPath}/{_projName}.Repositories/{repoName}", repo);
            Write($"{_projBasicPath}/{_projName}.IServices/{iServName}", iServ);
            Write($"{_projBasicPath}/{_projName}.Services/{servName}", serv);

            return $"{iRepo}\r\n{repo}\r\n{iServ}\r\n{serv}";
        }

        private void Write(string fileName, string content)
        {
            try
            {
                using var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
                using var sw = new StreamWriter(fs, Encoding.UTF8);
                sw.Write(content);
                sw.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Create the {fileName} failure:{ex.Message}");
            }
        }
    }
}
